package cn.zhm;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;


/**
 * 返回页面
 * @Author: ZhongHaoMing
 * @emali: zhonghaoming@bosssoft.com
 * @since: 1.8
 * @Date: 2021/10/26 - 11:13
 */
public class ReturnHtml {
    public static String ret(String path) {
        int status = 200;
        String str = "OK";
        StringBuilder responseInfo = new StringBuilder();
        String blank = " ";
        String CRLF = "\r\n";

        byte[] bytes = new byte[1024];
        StringBuilder content = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream("./target/classes"+path);
            while (fileInputStream.read(bytes)!=-1){
                content.append(new String(bytes,StandardCharsets.UTF_8));
            }
        }catch (Exception e){
            status = 404;
            str = "ERROR";
            content.delete(0,content.length());
            content.append("<h1>404</h1>");
        }

        int size = content.toString().getBytes().length;
        responseInfo.append(status).append(blank);
        responseInfo.append("HTTP/1.1").append(blank);
        responseInfo.append(str).append(CRLF);
        responseInfo.append("Date:").append(new Date()).append(CRLF);
        responseInfo.append("Server:").append("Server/0.0.1;charser=GBK").append(CRLF);
        responseInfo.append("Content-type:text/html").append(CRLF);
        responseInfo.append("Content-length").append(size).append(CRLF);
        responseInfo.append(CRLF);
        responseInfo.append(content.toString());
        return responseInfo.toString();
    }
}
